import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ProfileServiceProxy, TaskForModelDto, TaskServiceProxy, OutsourcingWorkFlowInputDto, OutsourcingWorkFlowStepUserDto, OutsouringTaskDto, UserServiceProxy, OutsourcingFormInputDto, OutsourcingWorkFlowServiceProxy, OutsourcingDto, SupplierServiceProxy, OutsouringServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { timingSafeEqual } from 'crypto';
import { SelectItem, SelectItemGroup } from 'primeng/api';


@Component({
    selector: 'flowapplyordinarycreate',
    templateUrl: './flowapplyordinarycreate.component.html',
    styleUrls: ['./flowapplyordinarycreate.component.css']

})

// 一般過程外包申請
export class FlowapplyordinarycreateComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('taskdataTable') taskdataTable: Table;
    @ViewChild('dataTable') dataTable: Table;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    filterText = '';
    active = false;
    saving = false;
    selectedCar3: string;
    task: TaskForModelDto = new TaskForModelDto();
    Outsourcings: OutsourcingDto[];
    workflow: OutsourcingWorkFlowInputDto = new OutsourcingWorkFlowInputDto();

    tasks: OutsouringTaskDto[];
    SupplierAyy: SelectItem[];

    taskType = 0;
    isReceived = true;
    isCompleted = false;
    suppliers: [];
    clonedOutsourcings: { [s: number]: OutsourcingDto; } = {};


    users: SelectItem[];
    stepusers: OutsourcingWorkFlowStepUserDto;

    constructor(injector: Injector,
        private _taskServiceProxy: TaskServiceProxy,
        private _outSourcingworkflowServiceProxy: OutsourcingWorkFlowServiceProxy,
        private _taskService: TaskService,
        private _supplierService: SupplierServiceProxy,
        private _outSourcingServiceProxy: OutsouringServiceProxy,
        private _userService: UserServiceProxy,
        private _profileService: ProfileServiceProxy) {
        super(injector);
    }
    show(taskId?: number): void {

        this._supplierService.getAllSupplierItems().subscribe(resultdata => {
            this.SupplierAyy = resultdata;
        });
        this._userService.getAllUserForDropDown2().subscribe(resultdata => {
            console.log(resultdata);
            this.users = resultdata;
        });


        this.filterText = '';
        this.task = new TaskForModelDto();
        this.workflow = new OutsourcingWorkFlowInputDto();
        this._taskService.clearOutSourcs();
        this.suppliers = [];
        this.primengTableHelper.totalRecordsCount = 0;
        this.primengTableHelper.records = new Array();
        //this.getTasks();
        this._outSourcingworkflowServiceProxy.buildWorkFlowCode().subscribe(flowcode => {
            this.workflow.code = flowcode;
            this.active = true;
            this.modal.show();
        });
    }

    // tslint:disable-next-line: use-life-cycle-interface
    ngOnInit(): void {

        this.stepusers = new OutsourcingWorkFlowStepUserDto();
        this.suppliers = [];
        this.primengTableHelper.records = null;
    }

    onShown(): void {
        //document.getElementById('Code').focus();
    }
    joinTask(data) {
        let outsourcing = this.Outsourcings.filter(x => x.taskForModelId === data.id)[0];

        if (outsourcing === undefined) {
            console.log(outsourcing);
            let _dto = new OutsourcingDto();
            _dto.taskForModelId = data.id;
            _dto.picNo = data.drawingCode;
            _dto.taskCode = data.taskCode;
            _dto.taskName = data.drawingName;
            _dto.taskCount = data.totalQuantity;
            _dto.outsouringAmount = 0;
            _dto.deliveryRate = null;
            _dto.workStatus = '';
            _dto.unitPrice = 0;
            this.Outsourcings.push(_dto);
        } else {
            this.notify.info('该任务已经在申请列表中！');
        }

        //this.createOrdinaryForm.show(task);
    }
    save(): void {
        let input = new OutsourcingFormInputDto();
        input.outSourcingDtos = this.Outsourcings;
        this.workflow.supplierUnit = this.suppliers.join(',');
        input.workFlowDto = this.workflow;
        input.stepUserDto = this.stepusers;
        this.saving = true;

        if (!this.stepusers.workShopLeader) {
            this.notify.info('请选择单位主管领导');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionModelManager) {
            this.notify.info('计划生产处型号主管');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionLeader) {
            this.notify.info('计划生产处主管处长');
            this.saving = false;
            return;
        }
        // tslint:disable-next-line: triple-equals
        if (this.Outsourcings.length == 0) {

            this.notify.info('未选择外协任务');
            this.saving = false;
            return;
        }
        this._outSourcingworkflowServiceProxy.createOrUpdateWorkFlow(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }
    close(): void {
        this.active = false;
        this.modal.hide();
    }
    getTasks(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._taskServiceProxy.getTaskForModel(
            this.taskType,
            this.filterText,
            this.isReceived,
            undefined,
            this.isCompleted,
            0,
            this.primengTableHelper.getSkipCount(this.paginator, event),
            this.primengTableHelper.getMaxResultCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
            this.tasks = result.items;
            _.forEach(this.tasks, viewItem => {
                this._outSourcingServiceProxy.getOutsouringApplyAmountForTaskId(viewItem.id)
                    .subscribe(amountresult => {
                        let currentD = this.tasks.find((element) => (element.id === viewItem.id));
                        currentD.outsourcingApplyAmount = amountresult.toString();
                    });
            });
        });
    }


    getOutsourcing(event?: LazyLoadEvent) {
        this.Outsourcings = this._taskService.getOutSourcings();
    }

    onRowEditInit(task: OutsourcingDto) {
        console.log(task);
        this.clonedOutsourcings[task.taskForModelId.toString()] = { ...task };
    }

    onRowEditSave(task: OutsourcingDto) {
        if (task.outsouringAmount > 0) {
            delete this.clonedOutsourcings[task.taskForModelId.toString()];
            this.notify.info(this.l('SavedSuccessfully'));
        } else {
            this.notify.info('申请数量不能小于0');
        }
    }

    onRowEditCancel(task: OutsourcingDto, index: number) {
        console.log(this.clonedOutsourcings[task.taskForModelId.toString()]);
        this.Outsourcings[index] = this.clonedOutsourcings[task.taskForModelId.toString()];
        delete this.Outsourcings[task.taskForModelId];
    }
    deleteRow(task: OutsourcingDto): void {
        let index = this.Outsourcings.indexOf(task);
        this.Outsourcings.splice(index, 1);
    }
}
